import Router from 'koa-router'
import Mock from 'mockjs'
import mockApis from '../mock'
import blog from './blog'
import user from './user'
import mq from '../mysql'
import uploadFile from '../utils/uploadFile'
import { routerBottom } from '../utils'

const router = new Router({
  prefix: '/blog',
})
router.get(
  '/api',
  async (ctx, next) => {
    await new Promise((resolve, _reject) => {
      setTimeout(() => {
        resolve(null)
      }, 3000)
    })
    next()
  },
  (ctx) => {
    ctx.body = 'blog_service已开启'
  }
)

router.post('/gitee/webhook', async (ctx) => {
  console.log('/gitee/webhook', ctx.request.body)
  ctx.body = {
    status: true,
    json: {
      a: 'b',
    },
  }
  return
})
mockApis.forEach((el) => {
  router.post(`/${el.api}`, (ctx) => {
    // 判断是否存在data字段
    const keys = Object.keys(el)
    let isData = false
    for (const key of keys) {
      if (key === 'data' || key.includes('data|')) {
        isData = true
        break
      }
    }
    if (!isData)
      return (ctx.body = {
        status: true,
        code: 0,
      })
    const data: { [key: string]: any } = {}
    for (const key in el) {
      if (key !== 'api') {
        data[key] = el[key]
      }
    }
    const resData = Mock.mock({
      mock: true,
      status: true,
      code: 0,
      ...data,
    })
    return (ctx.body = resData)
  })
})

router.post(
  '/addViewCount',
  async (ctx, next) => {
    await mq(`UPDATE global SET viewCount = viewCount+1`)
    next()
  },
  routerBottom
)

router.post(
  '/upDateImage',
  async (ctx, next) => {
    const result: any = await uploadFile(ctx)
    ctx.params.body = {
      status: result.status,
      msg: result.msg,
      data: {
        imgurl: result.path,
      },
    }
    next()
  },
  routerBottom
)
router.use('', blog.routes(), blog.allowedMethods())
router.use('', user.routes(), user.allowedMethods())
export default router
